﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.IO;

namespace FlightSearchServer
{
    class Logger : IParameterInspector
    {
        private static TextWriter writer = null;

        private static object locker = new object(); 

        public Logger()
        {

        }

        public Logger( string fileName) {
            lock (locker)
            {
                if ( writer == null)
                    writer = new StreamWriter(fileName);
            }
        }

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
            List<object> inputs = (List<object>)correlationState;
            DateTime startTime = (DateTime)inputs.ElementAt(inputs.Count - 1);
            DateTime endTime = DateTime.Now;
            TimeSpan ellapsed = endTime - startTime;
            if (writer == null)
            {
                Console.Write(operationName + " ");
                for (int i = 0; i < inputs.Count - 1; ++i )
                {
                    Console.Write(inputs[i] + ", ");
                }
                Console.WriteLine( "time ellapsed {0}", ellapsed);
            }
            else
            {
                lock (writer)
                {
                    writer.Write(operationName + " ");
                    for (int i = 0; i < inputs.Count - 1; ++i)
                    {
                        writer.Write(inputs[i] + ", ");
                    }
                    writer.WriteLine("time ellapsed {0}", ellapsed);
                    writer.Flush();
                }
            }

        }
        public object BeforeCall(string operationName, object[] inputs)
        {
            return new List<object>( inputs.Concat(new object[] { DateTime.Now }));
        }

    }
}
